1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.io;
18
19 import com.google.common.annotations.Beta;
20
21 import java.io.FilterInputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24
25 import javax.annotation.Nullable;
26
27
28
29
30
31
32
33 @Beta
34 public final class CountingInputStream extends FilterInputStream {
35
36 private long count;
37 private long mark = -1;
38
39
40
41
42
43
44 public CountingInputStream(@Nullable InputStream in) {
45 super(in);
46 }
47
48
49 public long getCount() {
50 return count;
51 }
52
53 @Override public int read() throws IOException {
54 int result = in.read();
55 if (result != -1) {
56 count++;
57 }
58 return result;
59 }
60
61 @Override public int read(byte[] b, int off, int len) throws IOException {
62 int result = in.read(b, off, len);
63 if (result != -1) {
64 count += result;
65 }
66 return result;
67 }
68
69 @Override public long skip(long n) throws IOException {
70 long result = in.skip(n);
71 count += result;
72 return result;
73 }
74
75 @Override public synchronized void mark(int readlimit) {
76 in.mark(readlimit);
77 mark = count;
78
79 }
80
81 @Override public synchronized void reset() throws IOException {
82 if (!in.markSupported()) {
83 throw new IOException("Mark not supported");
84 }
85 if (mark == -1) {
86 throw new IOException("Mark not set");
87 }
88
89 in.reset();
90 count = mark;
91 }
92 }